<?php

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\PinModel;
use app\shop\model\GoodsModel;
use app\shop\model\PinPriceModel;
use app\shop\model\SpecItemModel;
use app\shop\model\SpecModel;
use app\shop\model\SpecPriceModel;


class Pin extends Admin
{
    public function index()
    {
        $list = PinModel::getAllList();
        $item = $list->items();
        $page = $list->render();
        foreach ($item as $k=>$v){
            $item[$k]['time'] = $v['time']/3600;
        }

        return ZBuilder::make('table')
            ->setPageTitle('拼团管理')
            ->hideCheckbox()
            ->addColumns([
                ['goods_name','活动商品'],
                ['num','成团人数'],
                ['time','拼团时间/小时'],
                ['add_time','添加时间','datetime'],
                ['up_time','更新时间','datetime'],
                ['right_button','操作']
            ])
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->setRowList($item)
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){

            $this->store();
        }
        $goods_list = GoodsModel::getRes();

        $this->assign('goods_list', $goods_list);
        return $this->fetch();

    }

    public function edit($id=0)
    {
        if(request()->isPost()){
            $this->store();
        }
        $data = PinModel::getOne($id);
        $data['time'] = $data['time']/3600;
        $goods_list = GoodsModel::getRes();

        $this->assign('goods_list', $goods_list);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 获取商品规格
     */
    public function ajaxGetGoodsSpec()
    {
        $goods_id =  input('get.goods_id');
        $type =  input('get.type'); //add edit
        $goods_info = GoodsModel::getOne($goods_id);
        $type_id = $goods_info['type_id'];
        if($type_id == 0){
            //无商品模型
            $str = "<table class='table table-bordered' id='spec_input_tab' >";
            $str .="<tr>";
            $str .="<td><b>原价格</b></td>
                <td><b>拼团价格</b></td>
               <td><b>总库存</b></td>
               <td><b>拼团库存</b></td>
             </tr>";
            $str .= "<tr><td><input class='form-control' name='shop_price' value='{$goods_info['shop_price']}' readonly=''></td>
                <td><input class='form-control' name='pin_price' value='{$goods_info['pin_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)' onpaste='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)'></td>
                <td><input class='form-control' name='store_num' value='{$goods_info['store_num']}' readonly='' onkeyup='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)' onpaste='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)'></td>
                <td><input class='form-control' name='pinstore_num' value='{$goods_info['pinstore_num']}'>
                <input type='hidden' name='' value=''></td></tr></table>";
        }else{
            $spec_list = SpecModel::getIdList($type_id);
            $spec_item = [];
            foreach($spec_list as $k => $v){
                $spec_item[$v] = SpecItemModel::getIdList($v);
            }

            $items_id = SpecPriceModel::getKeyList($goods_id);
            $items_ids = [];
            foreach ($items_id as $k=>$v){
                $_item = explode('_', $v);
                $items_ids = array_merge($items_ids,$_item);
            }
            $items_ids = array_unique($items_ids);
            $items_has = [];    //该商品拥有的规格
            foreach ($items_ids as $k=>$v){
                foreach ($spec_item as $k2=>$v2){
                    if(in_array($v,$v2))
                        $items_has[$k2][] = $v;
                }
            }


            foreach ($items_has as $k => $v)
            {
                $spec_arr_sort[$k] = count($v);
            }

            asort($spec_arr_sort); //按照键值对关联数组进行升序排序
            foreach ($spec_arr_sort as $key =>$val)
            {
                $spec_arr2[$key] = $items_has[$key];
            }

            $clo_name = array_keys($spec_arr2);     //返回包含数组中所有键名的一个新数组

            $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积


            $spec = SpecModel::getColumn();

            $specItem = SpecItemModel::getColumn();

            $keySpecGoodsPrice = SpecPriceModel::getColumn($goods_id);
            $str = "<table class='table table-bordered' id='spec_input_tab' >";
            $str .="<tr>";
            // 显示第一行的数据
            foreach ($clo_name as $k => $v)
            {
                $str .=" <td><b>{$spec[$v]}</b></td>";
            }
            $str .="<td><b>原价格</b></td>
                <td><b>拼团价格</b></td>
               <td><b>总库存</b></td>
               <td><b>拼团库存</b></td>
             </tr>";
            // 显示第二行开始
            foreach ($spec_arr2 as $k => $v)
            {
                $str .="<tr>";
                $item_key_name = array();
                foreach($v as $k2 => $v2)
                {
                    $str .="<td class='link'>{$specItem[$v2]['item']}</td>";
                    $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
                }
                ksort($item_key_name);
                $item_key = implode('_', array_keys($item_key_name));
                $item_name = implode(' ', $item_key_name);

                isset($keySpecGoodsPrice[$item_key]['price']) ? false : $keySpecGoodsPrice[$item_key]['price'] = 0; // 价格默认为0
                isset($keySpecGoodsPrice[$item_key]['pin_price']) ? false : $keySpecGoodsPrice[$item_key]['pin_price'] = 0; // 价格默认为0
                isset($keySpecGoodsPrice[$item_key]['store_num']) ? false : $keySpecGoodsPrice[$item_key]['store_num'] = 0; //库存默认为0
                isset($keySpecGoodsPrice[$item_key]['pinstore_num']) ? false : $keySpecGoodsPrice[$item_key]['pinstore_num'] = 0; //库存默认为0

                $str .="<td><input class='form-control' name='item[$item_key][price]' value='{$keySpecGoodsPrice[$item_key]['price']}' readonly /></td>";
                $str .="<td><input class='form-control' name='item[$item_key][pin_price]' value='{$keySpecGoodsPrice[$item_key]['pin_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .="<td><input class='form-control' name='item[$item_key][store_num]' value='{$keySpecGoodsPrice[$item_key]['store_num']}' readonly onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .="<td><input class='form-control' name='item[$item_key][pinstore_num]' value='{$keySpecGoodsPrice[$item_key]['pinstore_num']}' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' />
                <input type='hidden' name='item[$item_key][grab_price]' value='{$keySpecGoodsPrice[$item_key]['grab_price']}' />
                <input type='hidden' name='item[$item_key][grabstore_num]' value='{$keySpecGoodsPrice[$item_key]['grabstore_num']}' /></td>";
                $str .="</tr>";
            }
        }

        $str .= "</table>";
        return $str;
    }



    public function delete($ids = 0)
    {
        $res = PinModel::del($ids);
        if($res){
            $this->success('删除成功',url('index'));
        }else{
            $this->error('删除失败');
        }
    }

    private function store()
    {
        $data = input('post.');

        $id = input('id',0);
        $validate = new \app\shop\validate\Pin();
//        if(!$validate->check($data)){
//            $this->error($validate->getError());
//        }
        $data['time'] = intval($data['time']*3600);

        if(isset($data['item']) && $data['item'])
        {

            foreach($data['item'] as $k => $v)
            {
                // 批量添加数据
                $v['price'] = trim($v['price']);
                $dataList[] = ['goods_id'=>$data['goods_id'],'key'=>$k,'key_name'=>$v['key_name'],'price'=>$v['price'],'pin_price'=>$v['pin_price'],'grab_price'=>$v['grab_price'],'store_num'=>$v['store_num'],'pinstore_num'=>$v['pinstore_num'],'grabstore_num'=>$v['grabstore_num']];

            }

            SpecPriceModel::del($data['goods_id']);

            db("spec_price")->insertAll($dataList);

        }else{
            //没有商品规格的
            GoodsModel::where('id',$data['goods_id'])->update(['pin_price'=>$data['pin_price'],'pinstore_num'=>$data['pinstore_num']]);
        }
        unset($data['item']);
        $res = PinModel::store($data, $id);
        if($res>=1||$res==0){
            $this->success('保存成功',url('index'));
        }else{
            $this->error('保存失败，请重试！');
        }
    }





}